<?php
	//error_reporting(0);
	set_time_limit(E_ALL);
	include 'simplehtmldom/simple_html_dom.php';
	include_once(dirname(__FILE__).'/dbutil.php');
	function saveRecord($table,$record,$db){
	    if(empty($table))
	    	return false;
	    if(!is_array($record) || empty($record))
	    	return false;
	    //$db = new DBUtil();
	    //$this->initDB();
	    $r = array();
	    foreach($record as $key=>$item){
	    	$r[$db->escape($key)] = $db->escape($item);
	    }
	    $cols = implode("," , array_keys($r));
	    $values = implode("','" , $r);
	    $sql = "insert into " . $db->escape($table) . " (" . $cols . ") values ('" . $values . "')";
	    return $db->query($sql) ? $db->getlastid() : false;
    }
	echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
	$baseUrl = 'https://xa.fang.anjuke.com/'; //需要修改
	// 西安安居客
	$url = $baseUrl;
	while(true){
		$recordList = array();
		// 西安房天下
		$listPage = file_get_html($url);
		//$listPage = file_get_contents('compress.zlib://http://newhouse.xian.fang.com/house/dianshang/');
		//echo $listPage
		if(empty($listPage)){
			break;
		}
		$list = $listPage->find('div[class=infos]');
		if(!empty($list)){
			foreach($list as $listItem){
				//var_dump(mb_convert_encoding($listItem->innertext,'utf-8','gbk'));
				$tmp = $listItem->find('span[class=items-name]');
				
				if(empty($tmp)){
					//echo 1;exit;
					continue;
				}
				$name = trim($tmp[0]->innertext);
				$tmp = $listItem->find('a[class=address]')[0]->find('span[class=list-map]');
				$adress = str_ireplace('&nbsp;','',trim($tmp[0]->innertext));
				$record = array();
				$record['house_name'] = $name ;
				$record['address'] = $adress;
				//$record['city'] = 'nanchang';
				//状态
				$record['status'] = 0;
				$recordList[] = $record;
				//break;
			}
			//var_dump($recordList);exit;
			$db = new DBUtil();
			//var_dump($recordList);exit;
			foreach($recordList as $item){
				$h = $db->getOneRow("select id from t_house where house_name = '".$db->escape($item['house_name'])."' ");
				if(empty($h)){
					// 保存楼盘信息
					saveRecord('t_house',$item,$db);
				}
			}
			$db->close();
		}
		$nextPage = $listPage->find('div[class=pagination]')[0]->find('span[class=curr-page]')[0]->next_sibling();
		while(!empty($nextPage) && $nextPage->tag != 'a' ){
			$nextPage = $nextPage->next_sibling();
		}
		if(!empty($nextPage) ){
			$url = $nextPage->href;
		}else{
			echo 'finish';
			break;
		}
		//sleep(30);
		echo $url.'<br/>';
	}
	
	// 删除html
	function removeHtml($value){
		return preg_replace('/<.*?<\/\w+>/','',$value);
	}
	// 删除全部空格
	function removeSpace($value){
		return preg_replace('/\s+/','',$value);
	}
?>